package com.mdxx.xczd.manager;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import org.videolan.libvlc.EventHandler;
import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.LibVlcException;
import org.videolan.vlc.Util;

/**
 * Created by MD-02 on 2017/4/20.
 */

public class VlcManager {
    private LibVLC mLibVLC = null;
    EventHandler em = null;
    private Context context;
    private String url;

    private static VlcManager vlcManager;
    private VlcManager(Context context){
        this.context = context;
        init();
    }

    public static VlcManager getInstance(Context context){
        if(vlcManager == null){
            synchronized (VlcManager.class) {
                if(vlcManager == null){
                    vlcManager = new VlcManager(context);

                }
            }
        }
        return vlcManager;
    }

    private void init(){
        em = EventHandler.getInstance();
        em.addHandler(handler);
        try {
            mLibVLC = Util.getLibVlcInstance();
        }catch (LibVlcException e) {
            e.printStackTrace();
        }
    }

    public void startPlayAudio(String rtspUrl) {
        url = rtspUrl;
            if (mLibVLC != null) {
                mLibVLC.setNetworkCaching(0);
                mLibVLC.playMRL(rtspUrl);
            }else{
                init();
            }
    }

    public void stopPlayAudio() {
        if(mLibVLC != null){
            mLibVLC.stop();
        }else{

        }
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.getData().getInt("event")) {
                case EventHandler.MediaPlayerPlaying:
                    break;
                case EventHandler.MediaPlayerPaused:
                    break;
                case EventHandler.MediaPlayerStopped:
                    break;
                case EventHandler.MediaPlayerEndReached:
                    break;
                case EventHandler.MediaPlayerVout:
                    break;
                case EventHandler.MediaPlayerPositionChanged:
                    break;
                case EventHandler.MediaPlayerEncounteredError:
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            startPlayAudio(url) ;
                        }
                    }, 500);
                    break;
                default:
                    break;
            }
        }
    };
}
